// 云文档 - 电子表格
import {HttpUtils} from '@srcUtils/utils';
import {httpClient} from '@srcUtils/req';
import {Handler} from '@srcTypes/route';
import {Request, Response} from 'express';
import {resp} from '@srcUtils/resp';
import {User} from '@srcDb/model/user';
import {queryUserInfo} from '@srcDb/redis/auth';
import {lark} from '@/config';

export const getSheetMeta = async (authToken: string, sheetToken: string) => {
    const url = HttpUtils.handleParamsPath(lark.env.api.DOCS_OPEN_API.SHEET.SHEETS_V2_META, [sheetToken]);
    return await httpClient.get({
        url,
        requireToken: true,
        token: authToken,
    });
};

export const getSheetMetaReq: Handler = async (req: Request, res: Response) => {
    const {sheetToken} = req.query;
    const {uuid} = req.body;
    if (typeof uuid !== 'string') {
        res.json(resp.setFail().setMsg('用户不存在！').collect());
        return;
    }
    const user: User | null = await queryUserInfo(uuid as string);
    if (user === null) {
        res.json(resp.setFail().setMsg('用户身份已过期，请重新验证用户身份').collect());
        return;
    }
    const sheetMetaRes = await getSheetMeta(user.access_token, sheetToken as string);
    console.log(sheetMetaRes);
};

export const deleteSheet: Handler = async (req: Request, res: Response) => {
    const token: string = await HttpUtils.getTokenFromRequest(req);
    const {sheetToken} = req.params;
    const url = HttpUtils.handleParamsPath(lark.env.api.DOCS_OPEN_API.SHEET.SHEETS_V2_FILE, sheetToken);
    const delRes = await httpClient.delete({
        url,
        requireToken: true,
        token,
    });
    const data = (delRes as any).data;
    res.json(resp.setCode(data.code).setData(data.data).setMsg(data.msg).collect());
};

export const createSheet: Handler = async (req: Request, res: Response) => {
    const token: string = await HttpUtils.getTokenFromRequest(req);
    const {folder_token, title} = req.body;
    const createRes = await httpClient.post({
        url: lark.env.api.DOCS_OPEN_API.SHEET.SHEETS_V3_CREATE,
        requireToken: true,
        token,
        data: {
            title,
            folder_token,
        },
    });
    const data = (createRes as any).data;
    res.json(resp.setCode(data.code).setData(data.data).setMsg(data.msg).collect());
};
